﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lg.Core.ImageHelper
{
    public class Captcha
    {
        private string[] codes = { "A", "1", "B", "2", "C", "3", "D", "4", "E", "5", "F", "6", "7", "G", "8", "H", "9", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        public string? Code { get; }
        private System.Random rand = new System.Random();
        public Captcha(int randomLength = 6)
        {
            //生成随机数
            for (int i = 0; i < randomLength; i++)
            {
                Code += codes[rand.Next(codes.Length)];
            }
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns>验证码图片png byte[]</returns>
        public byte[] GetBytes()
        {
            //开始画图
            using (System.Drawing.Bitmap img = new System.Drawing.Bitmap(90, 34))
            {
                using Graphics g = Graphics.FromImage(img);
                g.Clear(Color.White);
                for (int i = 0; i < 100; i++)
                {
                    //画背景线条
                    Pen p = new Pen(Color.FromArgb(rand.Next()));
                    var x1 = rand.Next(100);
                    var x2 = rand.Next(30);
                    var y1 = rand.Next(30);
                    var y2 = rand.Next(30);
                    g.DrawLine(p, x1, x2, y1, y2);
                }
                //画文字
                g.DrawString(this.Code, new Font("Consolas", 16f, FontStyle.Italic), Brushes.Black, 5, 5);
                //画图片的前景干扰点
                for (int i = 0; i < 500; i++)
                {
                    int x = rand.Next(img.Width);
                    int y = rand.Next(img.Height);
                    img.SetPixel(x, y, Color.FromArgb(rand.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);
                using MemoryStream MStream = new MemoryStream();
                img.Save(MStream, ImageFormat.Png);
                return MStream.ToArray();
            }
        }

        public string GetBase64()
        {
            byte[] bytes = this.GetBytes();
            return $"data:image/png;base64,{Convert.ToBase64String(bytes)}";
        }

        public static Captcha Build(int randomLength=6)
        {
            Captcha captcha = new Captcha(randomLength);
            return captcha;
        }
    }
}
